/*
 * scheduler.c
 * 
 * Copyright 2012 Laura <arual13@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "lib/scheduler.h"

//fabio
#include <sys/time.h>	/* for setitimer */
#include <signal.h>		/* for signal */
//end

//fabio -> variable to set the timer
struct itimerval it_val;
//end

//fabio
/* function prototype */
void TimerOff(void);
//end

// handler_active is an int flag defined in threads.h
//fabio
void TimerOff(void) {
  printf("Timer went off...\n");
  if(handler_active == 0){
	printf("\nTHE HANDLER IS NOT ACTIVE... it will be resumed\n");
	
	//The following two lines should stop the current thread and return the control to the handler...but something is wrong...
	//pause_thread(currentThread);
	//continue_handler();
  }
  if(handler_active == 1){
	printf("\nTHE HANDLER IS ACTIVE NOW!!!\n");
  }
}
//end

//~ int main(int argc, char **argv)
//~ {
    //~ /* Load configuration */
    //~ configuration *config = getConfigParams();
    //~ 
    //~ /* Initialize the seed for random nums */
    //~ srand(time(NULL));
    //~ 
    //~ if(config == NULL)
        //~ printf("%s\n","Error: Couldn't load the configuration file.");
    //~ else{
        //~ printf("%s\n","Initializing the scheduler...");
        //~ runScheduler(config);        
    //~ }
    //~ 
    //~ return 0;
//~ }

/* 
 * -Ready Queue: Initialized threads from the GUI - printQueue(readyQueue);
 * -Wait Queue: When threads stops using CPU and still have work to do..
 * -Running Queue: the thread that is running 
 * -Finish Queue: threads that finished, they don't participate in the raffle'
 */
 
int runScheduler(configuration *config)
{
    /* Scheduler Queues */    
    threadQueue* readyQueue = initializeThreads(config);
    threadQueue* runQueue =  newQueue(config->threads_num);
    threadQueue* waitQueue = newQueue(config->threads_num);
    threadQueue* finishQueue =  newQueue(config->threads_num);
    threadQueue* sourceQueue = readyQueue;
    threadNode* winner = NULL;
    long int lotteryMax = 0; // Total number of tickets
    
    for (long int i = 0; i < config->threads_num; i++) {
        lotteryMax += config->tickets_num[i];
    }
    
    printf("\nRunning in mode: %i \n", config->mode);
    
	
	//fabio
	if(config->mode == 1) {
		/* Upon SIGALRM, call DoStuff().
		* Set interval timer.  We want frequency in ms, 
		* but the setitimer call needs seconds and useconds. */
		if (signal(SIGALRM, (void (*)(int)) TimerOff) == SIG_ERR) {
			perror("Unable to catch SIGALRM");
			exit(1);
		}
		it_val.it_value.tv_sec =     config->quantum/1000;
		it_val.it_value.tv_usec =    (int)(config->quantum*1000) % 1000000;	
		it_val.it_interval = it_val.it_value;
		if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
			perror("error calling setitimer()");
			exit(1);
		}
	}
	//END
	
    /* While there are jobs to process*/
    while(readyQueue->head != NULL || waitQueue->head != NULL || runQueue->head != NULL) {
        
        long int number = getLotteryNum(lotteryMax);
        printf("Lottery: %ld \n",number);
        
        /* Selects the thread */
        sourceQueue = readyQueue;
        winner = getNextProcess(sourceQueue,number);
        
        /* We can add a tag to the queue to know which one it corresponds*/
        if (winner == NULL) {
            sourceQueue = waitQueue;
            winner = getNextProcess(sourceQueue,number);
        }
        
        /* Probably the process already finished */
        if (winner != NULL) {
            
            printf("Tread %ld wins! \n", winner->id);

            /* Sends the process to run, if they are in ready, send otherwise resubmit */
            moveElement(sourceQueue,runQueue,winner);
            
            
            /* TODO: PREEMPTIVE MODE*/
            if(config->mode == 1) {
                printf("*** PREEMPTIVE MODE ***\n");
			
			//Fabio
			units_to_complete = winner->work_left;			
			 
			if ( units_to_complete == 0 ) {
                    units_to_complete = 1;
            } else if ((winner->work_left - units_to_complete) < 0) {
                    units_to_complete = winner->work_left;
            }
			 
			printf("\nRunning thread %ld...\n", winner->id);
            pause_handler();
            start_thread(winner);
            printf("The thread came back!\n");
			//pause_thread(winner); /* Pause the thread */
			
			if ( units_to_complete == 0 ) {
                    winner->work_left -= 1;
            } else if ((winner->work_left - units_to_complete) < 0) {
                    winner->work_left = 0;
            } else {
                    winner->work_left -= units_to_complete;
            }
			
			winner->current_result += pi_result; /* TODO: Do something to the result*/
            printf("Units Completed: %ld Result: %Lf\n",units_to_complete, winner->current_result);
            }//end 
            
            /* NON-PREEMPTIVE MODE*/
            else {
    
                long double percentage = config->quantum/(double)100;
                units_to_complete = percentage*winner->work_units;
                
                if ( units_to_complete == 0 ) {
                    units_to_complete = 1;
                } else if ((winner->work_left - units_to_complete) < 0) {
                    units_to_complete = winner->work_left;
                }
                
                printf("\nRunning thread %ld...\n", winner->id);
                pause_handler();
                start_thread(winner);
                printf("The thread came back!\n");
                //pause_thread(winner); /* Pause the thread */
                
                /*Update the thread job!*/
                
                if ( units_to_complete == 0 ) {
                    winner->work_left -= 1;
                } else if ((winner->work_left - units_to_complete) < 0) {
                    winner->work_left = 0;
                } else {
                    winner->work_left -= units_to_complete;
                }
                
                winner->current_result += pi_result; /* TODO: Do something to the result*/
                printf("Units Completed: %ld Result: %Lf\n",units_to_complete, winner->current_result);

            }
            
            printf("Checking the result...\n");
            
            /* If there is still work to do, move it to waiting */
            if(winner->work_left > 0) {
                
                printf("Still there are %ld units to complete...\n", winner->work_left);
               
                moveElement(runQueue,waitQueue,winner);
                
            }
            /* No work, then it already finished */
            else{
                printf("Thread %ld finished...\n", winner->id);
                moveElement(runQueue,finishQueue,winner);
            }

    }
    }
    
    //unset the timer
	//fabio
	if(config->mode == 1) 
	{
		it_val.it_value.tv_sec =     0;
		it_val.it_value.tv_usec =    0;	
		it_val.it_interval = it_val.it_value;
		if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
			perror("error calling setitimer(0) with 0 seconds");
			exit(1);
		}
		else
		{
			printf("The timer has been stopped\n");
		}
	}
	//end
	
    printf("Done!\n");

    /* Release unsed memory 
    */
    freeQueue(readyQueue);
    freeQueue(waitQueue);
    freeQueue(runQueue);
    freeQueue(finishQueue);
    
	releaseMemory(config);

    return 0;
    
    
}

threadNode *getNextProcess(threadQueue* queue, int num)
{
    threadNode *node = getWinner(queue,num);

    return node;
        
}



long int getLotteryNum(long int limit)
{
    return rand()%limit; 
}


threadNode* getWinner(threadQueue* list, long int ticket)
{
    long int i;
    threadNode *node = NULL; 
    
    for(node = list->head; node; node = node->next) {
        
        long int tickets_num = node->tickets_num;
        
        for(i=0; i<tickets_num; i++)
        {
            if(ticket == node->tickets[i]) {
                return node;
            }
			/*printf("Looking Winner: %ld \n", node->id);*/
        }
    }
    
    return node;
        
}



int releaseMemory(configuration* config)
{

    free(config->tickets_num);
    free(config->work_units);
    free(config);
    
    return 0;
}



